<template>
  <!-- 人员弹窗 -->
  <a-modal
    centered
    :title="headerTitle"
    :visible="visible"
    ok-text=""
    width="1200px"
    @cancel="handleCancel"
    @ok="handleConfirm"
  >
    <a-row :gutter="10">
      <!-- 侧边栏 -->
      <a-col
        :span="6"
        style="border-right: 1px solid #d9d9d9"
      >
        <!-- 公司组织树搜索 -->
        <tree-organization
          v-if="visible"
          ref="treeOrganization"
          :checkable="isMutilple"
          :auto-select="false"
          :checkedKeys="treeCheckedKeys"
          :checkStrictly="checkStrictly"
          :project-dept-org-id="projectDeptOrgId"
          :org-query="orgQuery"
          @check="treeCheck"
          @select="treeSelect"
          @getData="getData"
          :defaultSelectedKeys="treeSelectKeys"
          :selected-keys.sync="treeSelectKeys"
          :select-options.sync="treeSelectOptions"
        />
      </a-col>
      <!-- 主内容 -->
      <a-col :span="18">
        <searchData
          ref="search"
          class="member-search"
          :showTitleName="false"
          :searchData="searchArr"
          @search="search"
        ></searchData>
        <div style="max-height: 150px; overflow: auto">
          <a-tag
            v-for="(person, index) in tableSelectedRows"
            :key="person.orgAndEmployerId"
            class="mb10"
            :closable="!person.isAdd"
            color="#108ee9"
            @close="() => handleClose(person, index)"
          >
            {{ person.name }}
          </a-tag>
        </div>

        <template v-if="isMutilple">
          <span class="mr10p">已选 {{tableSelectedRows.length}} 条</span>
          <a
            :disabled="cancalAll"
            @click="checkAll(false)"
          >全部取消</a>
        </template>
        <!-- 表格 -->
        <a-table
          :loading="tableLoading"
          :columns="columns"
          :row-key="record => record.orgAndEmployerId"
          :data-source="tableData"
          :row-selection="tableRowSelection"
          :pagination="{
              showQuickJumper: true,
              showSizeChanger: true,
              showTotal: total => `共搜索到 ${total} 条数据`
            }"
        />
      </a-col>
    </a-row>
    <!-- 页脚操作栏 -->
    <div
      v-if="isMutilple"
      slot="footer"
      class="btn_box"
    >
      <a-button
        type="primary"
        @click="handleCancel"
      >
        关闭
      </a-button>
      <a-button
        type="primary"
        @click="handleConfirm"
      >
        选中提交
      </a-button>
    </div>
    <div
      v-else
      slot="footer"
      class="btn_box"
    >
      <a-button
        type="default"
        @click="handleCancel"
      >
        取消
      </a-button>
      <a-button
        type="primary"
        @click="handleConfirm"
      >
        确定
      </a-button>
    </div>
  </a-modal>
</template>

<script>
import { STable } from '@/components' // 表格
import TreeOrganization from '@/components/businessComponents/TreeOrganization' // 树
import { getListByOrgs } from '@/api/commons'
const searchArr = [
  // 搜索框
  {
    name: '名称',
    type: 'input',
    value: 'nameLike'
  },
  {
    name: '员工编号',
    value: 'jobNumLike',
    type: 'input'
  },
  {
    name: '电话',
    value: 'phoneLike',
    type: 'input'
  }
]
const jobStatusList = [
  { id: 0, name: '离职' },
  { id: 1, name: '在职' },
  { id: 2, name: '见习' }
]
const mutilpleColumn = [
  {
    title: '序号',
    width: '80px',
    customRender(text, record, index) {
      return index + 1
    }
  },
  {
    title: '员工名称',
    dataIndex: 'name',
    width: '150px'
  },
  {
    title: '员工编号',
    dataIndex: 'jobNum',
    width: '100px'
  },
  {
    title: '状态',
    dataIndex: 'status',
    width: '100px',
    customRender(text, record, index) {
      return jobStatusList.find((item) => item.id == text).name
    }
  },
  {
    title: '电话号码',
    dataIndex: 'phone',
    width: '120px'
  },

  {
    title: '职务',
    ellipsis: true,
    dataIndex: 'postPNames',
    customRender(text, record, index) {
      return record.postPNames || '-'
    }
  }
]

const singleColumn = [
  {
    title: '员工名称',
    dataIndex: 'name'
  },
  {
    title: '电话号码',
    dataIndex: 'phoneNum'
  },
  {
    title: '当前所在岗位',
    ellipsis: true,
    dataIndex: 'postPNames',
    customRender(text, record, index) {
      return record.postPNames || '-'
    }
  }
]
export default {
  name: 'SelectPersonModal',
  components: {
    STable,
    TreeOrganization
  },
  props: {
    projectDeptOrgId: {
      type: String,
      default() {
        return ''
      }
    },
    // 表单
    form: {
      type: [Object],
      default() {
        return {}
      }
    },
    // 标题
    headerTitle: {
      type: String,
      default() {
        return '选择人员'
      }
    },
    // 是否多选
    isMutilple: {
      type: Boolean,
      default: true
    },
    // 禁用已选
    disabledOut: {
      type: Boolean,
      default: () => true
    },
    // 人员是否去重
    unRepeatPerson: {
      type: Boolean,
      default: () => true
    },
    //数据回显
    selectData: {
      type: Array,
      default() {
        return []
      }
    },
    // 主键字段名
    keyName: {
      type: String,
      default: () => 'userId'
    },
    checkStrictly: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      searchArr,
      visible: false,
      tableLoading: false,
      queryParam: {},
      treeCheckedKeys: [],
      treeSelectKeys: [],
      treeSelectOptions: [],
      tableSelectedKeys: [],
      tableSelectedRows: [],
      tableData: [],
      outTableData: [],
      allTreeData: [],
      treeKeys: []
    }
  },
  computed: {
    orgQuery() {
      return {
           baseOrgType: 0, // 是否基础组织 0否 1是
           containVirtual: 0, //是否包含虚拟组织 0包含 1 不包含
           systemOrgType: 1 //公司组织默认1
      }
    },
    tableRowSelection() {
      const { tableSelectedKeys } = this
      const type = this.isMutilple ? 'checkbox' : 'radio'
      return {
        type: type, // checkbox or radio
        selectedRowKeys: tableSelectedKeys,
        onChange: this.onSelectChange,
        hideDefaultSelections: true,
        getCheckboxProps: (record) => ({
          props: {
            disabled: record.isAdd
          }
        })
      }
    },
    columns() {
      if (this.isMutilple) {
        return mutilpleColumn
      }
      return singleColumn
    },
    cancalAll() {
      return this.tableSelectedRows.filter((v) => !v.isAdd).length == 0
    }
  },
  watch: {
    visible(e) {
      if (e) {
        if (!this.$refs.treeOrganization) {
          this.$nextTick(() => {
            this.tableData = []
            this.$refs.treeOrganization.getList().then((res) => {
              this.changeTreeChecked()
              // this.initPage()
            })
          })
        } else {
          // this.$nextTick(() => {
          //   this.initPage()
          // })
        }
      } else {
        // 重置关键词
        // this.nameLike = ''
        this.queryParam = {}
        this.$refs.search?.form.resetFields()
      }
    }
  },
  mounted() {},
  methods: {
    getData(data) {
      if (data.length) {
        this.$refs.treeOrganization.$refs.treeSearch.onExpand([data[0].id])
      }
      this.getLoggedPersonTreeNodedata(data)
      this.getTreeData(data)
    },
    getLoggedPersonTreeNodedata(data) {
      // 递归查询出当前登录岗位
      let curObj = null
      const loop = (list) => {
        for (let i = 0; i < list.length; i++) {
          const item = list[i]
          if (item.id == this.$currentPost().id) {
            curObj = item
            break
          }
          if (item.children && item.children.length) {
            loop(item.children)
          }
        }
      }
      loop(data)
      // 设置当前岗位父节点展开
      this.$refs.treeOrganization.$refs.treeSearch.onExpand([data[0].id, curObj.pid])
      // 设置当前select选中
      this.treeSelectKeys = [curObj.id]
      // 递归当前岗位数据，查询出当前岗位下所有项目部
      let ids = []
      const loop2 = (list) => {
        list.forEach((item, index) => {
          if (item.type == '2') ids.push(item.id)
          if (item.children) {
            loop2(item.children)
          }
        })
      }
      loop2([curObj])
      // 根据当前登录岗位下项目部查询各项目部下所有人
      this.treeKeys = ids
      this.getTableData(ids)
    },
    getTreeData(data) {
      for (let i = 0; i < data.length; i++) {
        const item = data[i]
        if (item.type == '2') {
          this.allTreeData.push(item)
        }
        if (item.children && item.children.length) {
          this.getTreeData(item.children)
        }
      }
    },
    checkAll(type) {
      if (type) {
        this.tableSelectedRows = this.tableData
        this.tableSelectedKeys = this.tableSelectedRows.map((v) => v.orgAndEmployerId)
      } else {
        const list = this.tableData.filter((v) => v.isAdd)
        this.tableSelectedRows = [...list]
        this.tableSelectedKeys = this.tableSelectedRows.map((v) => v.orgAndEmployerId)
        this.changeTreeChecked()
      }
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      let temp = []
      selectedRows.map((v) => {
        let res = this.tableSelectedRows.find((w) => v.orgAndEmployerId === w.orgAndEmployerId)
        if (!res) {
          temp.push(v)
        }
      })
      this.tableSelectedRows = this.tableSelectedRows.concat(temp)
      this.tableSelectedRows = this.tableSelectedRows.filter((v) => {
        return selectedRowKeys.find((w) => w === v.orgAndEmployerId)
      })

      this.tableSelectedKeys = this.tableSelectedRows.map((v) => v.orgAndEmployerId)
      // 表格数据勾选状态改变，联动树节点勾选改变
      this.changeTreeChecked()
    },
    changeTreeChecked() {
      const oids = []
      const temp = []
      const notemp = []
      this.tableSelectedRows.map((v) => {
        const has = oids.find((w) => w == v.orgId)
        if (!has) {
          oids.push(v.orgId)
        }
      })

      oids.map((v) => {
        const res = this.treeCheckedKeys.find((w) => w == v)
        if (!res) {
          notemp.push(v)
        }
      })

      setTimeout(() => {
        this.treeCheckedKeys = this.treeCheckedKeys.concat(notemp)
        this.treeCheckedKeys = this.treeCheckedKeys.filter((v) => {
          return oids.find((w) => {
            return w == v
          })
        })
      }, 100)
    },
    open(list) {
      this.visible = true
      this.outTableData = list
        ? list.map((v) => {
            if (this.disabledOut) v.isAdd = true
            v.orgAndEmployerId = this.unRepeatPerson ? v.id : v.orgId + '_' + v.id
            return v
          })
        : []
      this.tableSelectedKeys = this.$clone(this.outTableData.map((v) => v.orgAndEmployerId))
      this.tableSelectedRows = this.$clone(this.outTableData)
    },
    fuuniqueFunc(arr, uniId) {
      const res = new Map()
      return arr.filter((item) => !res.has(item[uniId]) && res.set(item[uniId], 1))
    },
    checkOrgsPersonData(checked, ids, treeCheck) {
      const treekeys = ids.filter((v) => {
        return this.allTreeData.find((w) => {
          return v == w.id
        })
      })
      const params = {
        ...this.queryParam,
        orgIds: treeCheck
      }
      this.tableLoading = true
      getListByOrgs(params).then((res) => {
        this.tableLoading = false
        this.tableSelectedKeys = []
        this.tableSelectedRows = []
        if (JSON.stringify(res.data) != '{}') {
          for (let idx in res.data) {
            const obj = res.data[idx]
            obj.forEach((item, idx1) => {
              item.orgId = idx
              item.orgAndEmployerId = this.unRepeatPerson ? item.id : idx + '_' + item.id
              if (this.disabledOut && this.outTableData.find((v) => v.orgAndEmployerId == item.orgAndEmployerId)) {
                item.isAdd = true
              }
              this.tableSelectedRows.push(item)
              this.tableSelectedKeys.push(item.orgAndEmployerId)
              this.tableSelectedKeys = Array.from(new Set(this.tableSelectedKeys))
              this.tableSelectedRows = this.fuuniqueFunc(this.tableSelectedRows, 'orgAndEmployerId')
              // console.log(obj,21111111)
              // let index = this.tableSelectedRows.findIndex((v) => {
              //   return v.orgAndEmployerId == item.orgAndEmployerId
              // })
              //  console.log(index,111111111)
              // if (checked) {
              //   if (index == -1) {
              //     this.tableSelectedRows.push(item)
              //     this.tableSelectedKeys.push(item.orgAndEmployerId)
              //   }
              // } else {
              //   if (index > -1) {
              //     this.tableSelectedKeys.splice(index, 1)
              //     this.tableSelectedRows.splice(index, 1)
              //   }
              // }
            })
          }
        } else {
          this.tableSelectedKeys = []
          this.tableSelectedRows = []
        }
        let temp = []
        this.outTableData.forEach((v) => {
          let has = this.tableSelectedRows.find((w) => v.orgAndEmployerId === w.orgAndEmployerId)
          if (!has) {
            temp.push(v)
          }
        })
        if (temp.length) {
          this.tableSelectedRows = this.tableSelectedRows.concat(temp)
          this.tableSelectedKeys = this.tableSelectedRows.map((v) => v.orgAndEmployerId)
          // 表格数据勾选状态改变，联动树节点勾选改变
          this.changeTreeChecked()
        }
      })
    },
    getTableData(orgIds) {
      const params = {
        ...this.queryParam,
        orgIds: orgIds
      }
      this.tableData = []
      this.tableLoading = true
      getListByOrgs(params)
        .then((res) => {
          this.tableLoading = false
          const list = []
          for (let idx in res.data) {
            const obj = res.data[idx]
            obj.forEach((item, index) => {
              item.orgId = idx
              item.orgAndEmployerId = this.unRepeatPerson ? item.id : idx + '_' + item.id
              if (this.disabledOut && this.outTableData.find((v) => v.orgAndEmployerId == item.orgAndEmployerId)) {
                item.isAdd = true
              }
              const is = list.find((v) => {
                return v.orgAndEmployerId == item.orgAndEmployerId
              })
              if (!is) {
                list.push(item)
              }
            })
          }
          // 选择查出所有数据，但列表不展示
          this.tableData = list
          if (this.selectData.length > 0) {
            this.selectData.map((item) => {
              this.tableData.map((tItem) => {
                if (!this.tableSelectedKeys.includes(tItem.id) && item[this.keyName] == tItem[[this.keyName]]) {
                  this.tableSelectedRows.push(tItem)
                  this.tableSelectedKeys.push(tItem.id)
                }
              })
            })
            this.changeTreeChecked()
          }
        })
        .catch(() => {
          this.tableLoading = false
        })
    },
    //点击复选框
    treeCheck(checkedKeys, e) {
      this.treeCheckedKeys = this.checkStrictly ? checkedKeys.checked : checkedKeys
      let keys = [e.node.dataRef.id]
      this.checkOrgsPersonData(e.checked, keys, this.checkStrictly ? checkedKeys.checked : checkedKeys)
      // this.getTableData(true)
    },
    treeSelect(e, n) {
      //点击树，不是点击复选框
      if (n.selected) {
        const datas = n.selectedNodes[0].data.props.dataRef
        const ids = []
        const loop = (list) => {
          list.forEach((item, index) => {
            if (item.type == '2') ids.push(item.id)
            if (item.children) {
              loop(item.children)
            }
          })
        }
        loop([datas])
        this.treeKeys = ids
        this.getTableData(ids)
      } else {
        this.treeKeys = this.allTreeData.map((v) => v.id)
      }
    },
    handleClose(removedPerson, index) {
      console.log(this.tableSelectedRows, '222222222')
      const key = this.tableSelectedRows[index]
      this.tableSelectedKeys.splice(index, 1)
      this.tableSelectedRows.splice(index, 1)
      this.changeTreeChecked()
    },
    handleConfirm() {
      let temp = []
      if (!this.selectData.length) {
        temp = !this.disabledOut
          ? this.tableSelectedRows
          : this.tableSelectedRows.filter((v) => {
              return !this.outTableData.find((w) => w.orgAndEmployerId === v.orgAndEmployerId)
            })
      } else {
        temp = this.tableSelectedRows
      }
      this.visible = false
      this.$emit('confirm', temp)
    },
    // 头部搜索
    search(param) {
      if (param && Object.keys(param).length) {
        this.queryParam = {
          ...param
        }
      }
      this.getTableData(this.treeKeys)
    },
    handleCancel() {
      this.visible = false
    }
  }
}
</script>
<style lang="less" scoped>
.ellipsis {
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  word-break: break-all;
  white-space: nowrap;
}
</style>
